"""
数据库管理模块
负责存储和管理Git提交历史数据
"""
from typing import Dict, List
from pymongo import MongoClient
import logging

class DBManager:
    def __init__(self, connection_string: str, db_name: str):
        self.client = MongoClient(connection_string)
        self.db = self.client[db_name]
        self.commits = self.db.commits
        self.files = self.db.files
        self.logger = logging.getLogger(__name__)
        
        # 创建索引
        self.commits.create_index('commit_id', unique=True)
        self.files.create_index('file_path')

    def save_commit(self, commit_data: Dict) -> bool:
        """保存提交信息到数据库
        
        Args:
            commit_data: 提交信息字典
            
        Returns:
            bool: 是否保存成功
        """
        try:
            self.commits.update_one(
                {'commit_id': commit_data['commit_id']},
                {'$set': commit_data},
                upsert=True
            )
            return True
        except Exception as e:
            self.logger.error(f"保存提交信息失败: {str(e)}")
            return False

    def save_file_history(self, file_history: Dict) -> bool:
        """保存文件历史记录
        
        Args:
            file_history: 文件历史信息
            
        Returns:
            bool: 是否保存成功
        """
        try:
            self.files.update_one(
                {'file_path': file_history['file_path']},
                {'$push': {'history': file_history}},
                upsert=True
            )
            return True
        except Exception as e:
            self.logger.error(f"保存文件历史失败: {str(e)}")
            return False

    def get_latest_commit(self) -> Dict:
        """获取最新的提交记录"""
        return self.commits.find_one(sort=[('date', -1)]) 